<template>
  <div class="login">
    <div v-if="isLogin">
      <header>
        <van-icon name="cross" size=".7rem" @click="goback"/>
      </header>
      <div v-if="login_type === 0" class="type_0">
        <div class="tips_box">
          <h3>登录</h3>
          <div class="tips" :class="!tips ? 'hidden' : ''">{{tip}}</div>
        </div>
        <div class="username">
          <van-field class="username_inp" v-model="account" placeholder="用户名/手机号" :clearable="true" :disabled="btn1"/>
        </div>
        <div class="psw">
          <van-field class="psw_inp" v-model="password" placeholder="请输入密码" type="password" :clearable="true" :disabled="btn1"/>
          <div class="forget_psw" @click="toForget">忘记密码</div>
        </div>
      </div>
      <div v-else-if="login_type === 1" class="type_1">
        <div class="tips_box">
          <h3>短信验证码登录</h3>
          <div class="tips" :class="!tips ? 'hidden' : ''">{{tip}}</div>
        </div>
        <div class="username">
          <van-field class="username_inp" v-model="phone" placeholder="请输入手机号码" :clearable="true" :disabled="btn1"/>
        </div>
        <div class="psw">
          <van-field class="psw_inp" v-model="captcha" placeholder="验证码" type="password" :clearable="true" :disabled="btn1"/>
          <div class="send_code" v-if="unSend" @click="getCode('PersonalLogin')">发送</div>
          <div class="send_code" v-else><van-count-down
            millisecond
            ref="countDown"
            :time="time"
            format="ss s"
            @finish="timeFinish"
          /></div>
        </div>
      </div>
      <div class="btn_box">
        <van-button class="btn" color="#FF2A1F" :disabled="btndisabled" :loading="btnlonding" loading-text="登录中..." @click="login">登录</van-button>
      </div>
      <div class="login_type">
        <span v-if="login_type === 1" @click="changeLogin(0)">账号密码登录</span>
        <span v-else-if="login_type === 0" @click="changeLogin(1)">短信验证码登录</span>
        <span @click="tabLogin(0)">新用户注册</span>
      </div>
      <div class="wechat_login">
        <img :src="$img('wechat_active.png')" @click="wechatLogin">
      </div>
    </div>
    <div v-else>
      <header>
        <van-icon name="arrow-left" size=".7rem" @click="tabLogin(1)"/>
      </header>
      <div class="type_1">
        <div class="tips_box">
          <h3 v-if="wxinfo === ''">{{forget ? '新用户注册' : '重置密码'}}</h3>
          <h3 v-else>绑定手机号</h3>
        </div>
        <div class="username">
          <van-field class="username_inp" v-model="phone" placeholder="请输入手机号码" :clearable="true" :disabled="btn1" autocomplete="new-password"/>
        </div>
        <div class="psw">
          <van-field class="psw_inp" v-model="captcha" placeholder="验证码" type="text" :clearable="true" :disabled="btn1" autocomplete="new-password"/>
          <div class="send_code" v-if="unSend" @click="getCode('sms_setpassword')">发送</div>
          <div class="send_code" v-else><van-count-down
            millisecond
            :time="time"
            format="ss s"
            @finish="timeFinish"
          /></div>
        </div>
        <div class="username" v-if="wxinfo === ''">
          <van-field class="username_inp" v-model="password" type="password" :placeholder="`请输入${forget ? '' : '新'}密码(6-12位数字字母)`" :clearable="true" :disabled="btn1" autocomplete="new-password"/>
        </div>
      </div>
      <div class="btn_box">
        <van-button v-if="wxinfo === ''" class="btn" color="#FF2A1F" :disabled="btndisabled" :loading="btnlonding" :loading-text="forget ? '注册中...' : '重置中...'" @click="signUp">{{forget ? '注册' : '重置'}}</van-button>
        <van-button v-else class="btn" color="#FF2A1F" :disabled="btndisabled" :loading="btnlonding" loading-text="绑定中" @click="binding">绑定</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import config from '@/config/config'
export default {
  data () {
    return {
      account: '',
      password: '',
      btndisabled: true,
      btnlonding: false,
      btn1: false,
      tips: false,
      login_type: 0,
      phone: '',
      captcha: '',
      time: 60 * 1000,
      unSend: true,
      isLogin: 1,
      tip: '填写错误',
      forget: 1,
      nextUrl: '/center',
      wxinfo: '',
      spread: ''
    }
  },
  watch: {
    account (val) {
      if (val !== '') {
        this.btndisabled = false
      }
    },
    password (val) {
      if (val !== '') {
        this.btndisabled = false
      }
    },
    phone (val) {
      if (val !== '') {
        this.btndisabled = false
      }
    }
  },
  methods: {
    ...mapMutations(['SET_TOKEN', 'SET_UINFO']),
    login () {
      this.tips = false
      if (this.login_type === 0 && (this.account === '' || this.password === '')) {
        this.$dialog({ message: '账号或者密码不能为空' })
        return false
      } else if (this.login_type === 1 && (this.phone === '' || this.captcha === '')) {
        this.$dialog({ message: '手机号或者验证码不能为空' })
        return false
      }
      this.btndisabled = true
      this.btnlonding = true
      this.btn1 = true
      this.$axios.post('/api/login', {
        account: this.account,
        password: this.password
      }).then(res => {
        if (res.status === 200) {
          this.$store.commit('SET_TOKEN', res.data.token)
          this.$store.commit('SET_RONG_TOKEN', res.data.rongcloud_token)
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('RongToken', res.data.rongcloud_token)
          this.$axios.get('/api/user').then(res => {
            if (res.status === 200) {
              this.$store.commit('SET_UINFO', res.data)
              localStorage.setItem('uinfo', JSON.stringify(res.data))
              this.$router.replace(this.nextUrl)
            }
          })
        } else {
          this.tip = res.msg
          this.tips = true
        }
        this.btndisabled = false
        this.btnlonding = false
        this.btn1 = false
      })
    },
    changeLogin (type) {
      this.phone = ''
      this.password = ''
      this.account = ''
      this.captcha = ''
      this.login_type = type
    },
    getCode (action) {
      if (this.btnlonding) {
        return
      }
      if (this.phone === '' && !/^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.phone)) {
        this.$dialog({ message: '手机号格式不正确' })
        return false
      }
      this.unSend = false
      this.tips = false
      this.$axios.post('/api/sms_send', {
        phone: this.phone,
        action_id: action
      }).then(res => {
        if (res.status === 400) {
          this.tip = res.msg
          this.tips = true
        }
      })
    },
    timeFinish () {
      this.unSend = true
    },
    toForget () {
      this.forget = 0
      this.phone = ''
      this.password = ''
      this.account = ''
      this.captcha = ''
      this.btndisabled = false
      this.btnlonding = false
      this.btn1 = false
      this.isLogin = 0
    },
    signUp () {
      if (this.captcha === '' || this.password === '' || this.phone === '') {
        this.$dialog({ message: '请把信息填写完整' })
        return false
      }
      if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.phone)) {
        this.$dialog({ message: '手机号格式不正确' })
        return false
      }
      if (this.password.length < 6 || this.password.length > 12 || !/^[0-9a-zA-Z]+$/.test(this.password)) {
        this.$dialog({ message: '密码格式不正确' })
        return false
      }
      this.btndisabled = true
      this.btnlonding = true
      this.btn1 = true
      this.$axios.post(this.forget ? '/api/register' : '/api/register/reset', {
        captcha: this.captcha,
        account: this.phone,
        password: this.password,
        spread: ''
      }).then(res => {
        if (res.status === 200) {
          this.$dialog({ message: this.forget ? '注册成功' : '重置成功' })
          this.isLogin = true
        } else {
          this.$dialog({ message: res.msg })
          return false
        }
        this.btndisabled = false
        this.btnlonding = false
        this.btn1 = false
      })
    },
    tabLogin (type) {
      this.phone = ''
      this.password = ''
      this.account = ''
      this.captcha = ''
      this.btndisabled = false
      this.btnlonding = false
      this.btn1 = false
      this.isLogin = type
      this.forget = 1
    },
    goback () {
      this.$router.go(-1)
    },
    wechatLogin () {
      location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.wxappID}&response_type=code&scope=snsapi_userinfo&redirect_uri=${encodeURIComponent(window.location.href)}#wechat_redirect`
    },
    getWXInfo (code) {
      this.$axios.get('/api/wechat/officialAccount', {
        params: {
          code
        }
      }).then(res => {
        if (res.status === 200) {
          if (res.data.register_status === 'YES') {
            this.$store.commit('SET_TOKEN', res.data.user.token)
            this.$store.commit('SET_RONG_TOKEN', res.data.user.rongcloud_token)
            localStorage.setItem('token', res.data.user.token)
            localStorage.setItem('RongToken', res.data.user.rongcloud_token)
            this.$axios.get('/api/user').then(res => {
              if (res.status === 200) {
                this.$store.commit('SET_UINFO', res.data)
                localStorage.setItem('uinfo', JSON.stringify(res.data))
                this.$router.replace(this.nextUrl)
              }
            })
          } else if (res.data.register_status === 'NO') {
            this.wxinfo = res.data.wechat_user
            this.isLogin = false
          }
        } else {
          this.$toast(res.msg)
        }
      })
    },
    binding () {
      if (this.captcha === '' || this.phone === '') {
        this.$dialog({ message: '请把信息填写完整' })
        return false
      }
      if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.phone)) {
        this.$dialog({ message: '手机号格式不正确' })
        return false
      }
      this.wxinfo.account = this.phone
      this.wxinfo.captcha = this.captcha
      this.$axios.post('/api/user/wechat_register', this.wxinfo).then(res => {
        if (res.status === 200) {
          this.$store.commit('SET_TOKEN', res.data.user.token)
          this.$store.commit('SET_RONG_TOKEN', res.data.user.rongcloud_token)
          localStorage.setItem('token', res.data.user.token)
          localStorage.setItem('RongToken', res.data.user.rongcloud_token)
          this.$axios.get('/api/user').then(res => {
            if (res.status === 200) {
              this.$store.commit('SET_UINFO', res.data)
              localStorage.setItem('uinfo', JSON.stringify(res.data))
              this.$router.replace(this.nextUrl)
            }
          })
        } else {
          this.$toast('微信登陆失败,请重新登陆')
          this.$router.replace(`/login?${this.redirect === '' ? '' : 'redirext=' + this.redirect}`)
        }
      })
    }
  },
  created () {
    if (this.$route.query.redirect) {
      this.nextUrl = this.$route.query.redirect
    }
    if (this.$route.params.timeout) {
      this.nextUrl = this.$route.params.redirect
      // this.$dialog({ message: '用户信息已过期,请重新登录' })
    }
    if (this.$route.query.code) {
      this.getWXInfo(this.$route.query.code)
    }
    if (this.$route.query.spread) {
      this.spread = this.$route.query.spread
      this.isLogin = false
    }
  }
}
</script>

<style lang="scss">
.login{
  padding: .67rem .21rem 0;
  header{
    display: flex;
    align-items: center;
  }
  .hidden{
    visibility: hidden;
  }
  .tips_box{
    margin-top: .56rem;
    padding-left: .33rem;
    h3{
      font-size: .38rem;
      color: #333333;
      font-weight: bold;
    }
    .tips{
      color: #ff3029;
      font-size: .25rem;
      margin-top: .1rem;
    }
  }
  .username{
    margin-top: .65rem;
    padding-bottom: .25rem;
    border-bottom: .02rem solid #f0f0f0;
    .username_inp{
      height: .46rem;
      color: #333333;
      font-size: .33rem;
      padding-top: 0;
      padding-bottom: 0;
    }
  }
  .psw{
    margin-top: .65rem;
    border-bottom: .02rem solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .psw_inp{
      width: 5.25rem;
      height: .46rem;
      color: #333333;
      font-size: .33rem;
      padding-top: 0;
      padding-bottom: 0;
      border: unset;
      outline: none;
      &::after{
        border-bottom: unset !important;
      }
    }
    .forget_psw{
      height: .46rem;
      border-left: .02rem solid #cccccc;
      font-size: .29rem;
      color: #666666;
      width: 1.58rem;
      text-align: center;
      line-height: .46rem;
    }
    .send_code{
      width: 1.27rem;
      height: .67rem;
      background: #FF2A1F;
      border-radius: .38rem;
      color: #ffffff !important;
      font-size: .29rem;
      font-weight: 500;
      text-align: center;
      line-height: .67rem;
      display: flex;
      align-items: center;
      justify-content: center;
      .van-count-down{
        color: #ffffff;
        font-size: .29rem;
      }
    }
  }
  .btn_box{
    height: .92rem;
    margin-top: .75rem;
    display: flex;
    .btn{
      width: 100%;
      height: 100%;
      color: #ffffff;
      font-size: .33rem;
      border-radius: .17rem;
    }
  }
  .login_type{
    display: flex;
    justify-content: space-between;
    color: #999999;
    font-size: .25rem;
    margin-top: .33rem;
  }
  .wechat_login{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 1rem;
  }
}
.type_0{
  .psw{
    padding-bottom: .38rem;
  }
}
.type_1{
  .psw{
    padding-bottom: .17rem;
  }
}
</style>
